package com.czk.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.gulimall.order.dao.OrderItemDao;
import com.czk.gulimall.order.entity.OrderEntity;
import com.czk.gulimall.order.entity.OrderItemEntity;
import com.czk.gulimall.order.entity.OrderReturnReasonEntity;
import com.czk.gulimall.order.service.OrderItemService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;


@Service("orderItemService")
@RabbitListener(queues = {"hello-java-queue"})
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 参数可以写以下类型：
     * 1 org.springframework.message Message message
     * 原生消息类型，有消息头和消息体
     * 2 发送的消息类型 OrderReturnReasonEntity
     * <p>
     * 3 Channel channel：当前传输的数据通道
     * <p>
     * Queue:可以很多人来监听，只要收到消息，队列删除消息，而且只能一个收到此消息
     * 场景：
     * 订单服务启动多个
     * 只有当前消息处理完，才会去接收下一个消息
     *
     * @param msg
     */
    // @RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage(Message msg, OrderReturnReasonEntity orderReturnReasonEntity, Channel channel) {
        System.out.println(msg);
        System.out.println(orderReturnReasonEntity);
        // 当前传输队列的用到
        System.out.println(channel);

        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        System.out.println("deliveryTag=" + deliveryTag);

        // 给消息队列服务器回复已经签收
        try {
            if (deliveryTag % 2 == 0) {
                // false非批量签收
                channel.basicAck(deliveryTag, false);
            } else {
                // 拒收
                /**
                 * deliveryTag tag号码
                 * 参数二：是否批量
                 * 参数三：是否重新入队
                 */
                channel.basicNack(deliveryTag, false, true);
            }

        } catch (IOException e) {
            // 网络中断
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void receiveMessage2(OrderEntity orderEntity) {
        System.out.println(orderEntity);
    }


}